﻿using AuthCenter.Domain;
using AuthCenter.ErorCode;
using AuthCenter.Infrastructure;
using AuthCenter_API.Write.Applications.Commands.Audit;
using AutoMapper;
using MediatR;

namespace AuthCenter_API.Write.Applications.CommandHandlers.Audit
{
    public class AuditUpdCommandHandler : IRequestHandler<AuditUpdCommand, APIResult<object>>
    {
        private readonly IBaseRepository<ShenPiModel> _shenpiRepository;
        private readonly IMapper _mapper;

        public AuditUpdCommandHandler(IBaseRepository<ShenPiModel> shenpiRepository, IMapper mapper)
        {
            _shenpiRepository = shenpiRepository;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AuditUpdCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.UpdSuccess;
            result.Message = APIEnum.UpdSuccess.Desc();
            ShenPiModel shenpi = _mapper.Map<ShenPiModel>(request);
            shenpi.State = 0;
            shenpi.CreateTime = DateTime.Now;
            var exist = _shenpiRepository.GetAll().Any(x => x.UserName == request.UserName && x.ShenId != request.ShenId);
            if (exist)
            {
                result.Code = APIEnum.AddFail;
                result.Message = APIEnum.AddFail.Desc() + "名称不能重复，请重新输入";
                return await Task.FromResult(result);
            }
            await _shenpiRepository.Update(shenpi);
            return await Task.FromResult(result);
        }
    }
}
